import {Component, OnInit} from '@angular/core';
import {BasePage} from '../../common/basePage';
import {AlertController, Events, ModalController, NavController, ToastController} from '@ionic/angular';
import {ActivatedRoute} from '@angular/router';
import {FormBuilder} from '@angular/forms';
import {HttpService} from '../../services/http.service';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {AppConfig} from '../../common/app-config.enum';
import {Storage} from '@ionic/storage';
import {IframePageComponent} from '../../components/iframe-page/iframe-page.component';

/**
 * 实名认证(存管开户)
 */
@Component({
  selector: 'app-user-account',
  templateUrl: './user-account.page.html',
  styleUrls: ['./user-account.page.scss'],
})
export class UserAccountPage extends BasePage implements OnInit {

  // 当前角色
  userRole: number;
  // 用户类型
  userType: number;

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController,
              private modalCtrl: ModalController,
              private alertCtrl: AlertController,
              private events: Events,
              private storage: Storage,
              private routeInfo: ActivatedRoute,
              private fb: FormBuilder,
              private service$: HttpService,
  ) {
    super(navCtrl, toastCtrl);
  }

  ngOnInit() {
    // 传递的userRole为字符串，需要转为数字(空字符串*1等于0)
    this.userRole = this.routeInfo.snapshot.params['userRole'] * 1 || null;
    // 读取userType
    this.routeInfo.data
      .subscribe(resolve => {
        this.userType = resolve['userType'];
      });
  }

  // 前往银行开户
  async openConfirm() {
    if (this.userRole) {
      await this.presentAlertConfirm();
    } else {
      this.showToast('请选择角色');
    }
  }

  // 提示开通存管
  private async presentAlertConfirm() {
    const roleType = this.userRole === 1 ? '出借人' : '借款人';
    const actionType = this.userRole === 1 ? '出借投资等操作，无法申请借款' : '借款申请，无法出借投资';
    const alert = await this.alertCtrl.create({
      header: '提示',
      message: '<p style="font-size: 14px;">每位用户只可开通一种账户角色，当前选择角色为<strong style="color:#F37938">'
      + roleType + '</strong>，开通后<strong style="color:#F37938">只可进行'
      + actionType + '</strong>，您确定要开通么？</p>',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        }, {
          text: '确定',
          handler: () => {
            this.goBank();
          }
        }
      ]
    });
    await alert.present();
  }

  private async goBank() {
    this.service$.doRequest(UrlAndOPT.create_account, {userRole: this.userRole})
      .subscribe(async (obj) => {
        if (obj) {
          // 打开资金存管开户页面model
          const modal = await this.modalCtrl.create({
            component: IframePageComponent,
            componentProps: {
              title: '资金存管开户',
              url: obj['url']
            }
          });
          await modal.present();
          // 关闭model后，确认用户角色状态
          await modal.onDidDismiss();
          this.sureUserAccount(async (obj2) => {
            if (obj2[AppConfig.USER_ROLE_KEY]) { // 已开通
              console.log('成功开通账户存管，角色：' + (obj2[AppConfig.USER_ROLE_KEY] === 1 ? '出借人' : '借款人'));
              // 更新本地用户状态
              const userInfo = await this.storage.get(AppConfig.USER_INFO);
              await this.storage.set(AppConfig.USER_INFO, {...userInfo, [AppConfig.USER_ROLE_KEY]: obj2[AppConfig.USER_ROLE_KEY]});
              // 发出流程变化通知
              this.events.publish(AppConfig.TOPIC_UNDO_LIST);
              this.doPop();
            } else {
              console.log((this.userRole === 1 ? '出借人' : '借款人') + '：资金存管开通失败');
              this.doPop();
            }
          });
        }
      });
  }

  // 确认存管账户状态
  private sureUserAccount(callback) {
    this.service$.doRequest(UrlAndOPT.auth_user_role)
      .subscribe(obj => {
        callback(obj);
      });
  }

}
